package com.knife.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * HTML发布类
 * @author Knife
 *
 */
public class HTMLPublish {
	static File newfile;
	static String content;
	static String oldpath;
	static String newpath;
	static BufferedReader br;
	static BufferedWriter bw;
	static String templine;
	
	public static void pub(File pubfile,String dir){
		oldpath="/html" + dir;
		newpath="/wwwroot" + dir;
		newfile=new File(pubfile.getAbsolutePath().replace(oldpath.replace("/", File.separator), newpath.replace("/", File.separator)));
		if (!(newfile.getParentFile().exists())) {
			newfile.getParentFile().mkdirs();
		}
		content="";
		try {
			if(pubfile.canRead()){
				content = org.apache.commons.io.FileUtils.readFileToString(pubfile, "UTF-8");
				if(content.length()<=1024*1024){
					content = content.replace(oldpath, "/");
					org.apache.commons.io.FileUtils.writeStringToFile(newfile,content,"UTF-8");  
				}else{
					br = new BufferedReader(new FileReader(pubfile));
					bw = new BufferedWriter(new FileWriter(newfile));
					templine = br.readLine();
					while(templine != null){
						//写文件
						templine = templine.replace(oldpath, "/");
						bw.write(templine + "\r\n"); //只适用Windows系统
						//继续读文件
						templine = br.readLine();
					}
					bw.close();
					br.close();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void unpub(File pubfile,String dir){
		oldpath="/html" + dir;
		newpath="/wwwroot" + dir;
		newfile=new File(pubfile.getAbsolutePath().replace(oldpath.replace("/", File.separator), newpath.replace("/", File.separator)));
		if (newfile.exists()) {
			newfile.delete();
		}
	}

}
